package com.itheima.interceptor;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.itheima.domain.db.Admin;
import com.itheima.domain.db.User;
import com.itheima.util.ConstantUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Duration;

@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");

        if (StrUtil.isNotBlank(token)) {
            //前端人员喜欢在token前面加上"Bearer ",所以我们需要移除掉
            token = token.replaceAll("Bearer ", "");
            String value = stringRedisTemplate.opsForValue().get(ConstantUtil.ADMIN_TOKEN + token);
            if (StrUtil.isNotBlank(value)) {
                Admin admin = JSON.parseObject(value, Admin.class);
                if (admin!=null) {
                    AdminHolder.set(admin);
                    
                    //续期
                    stringRedisTemplate.opsForValue().set(ConstantUtil.ADMIN_TOKEN+token,value, Duration.ofHours(1));
                    return true;
                }
            }
        }

        response.sendError(401);
        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AdminHolder.remove();
    }
}